<template>
  <div class="mod-user">
    <div class="listHead">
      <p>
        <el-button
          v-if="isAuth('sys:user:save')"
          type="primary"
          @click="addOrUpdateHandle()"
          class="add"
          >新增</el-button
        >
        <el-button
          v-if="isAuth('sys:user:delete')"
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >删除</el-button
        >
        <span v-if="this.dataListSelections.length == 1" class="spanwrap">
          <el-button
            type="primary"
            @click="examineHandle()"
            :disabled="examineStatus"
            >审核</el-button
          >
          <el-button
            type="primary"
            @click="unexamineHandle()"
            :disabled="unexamineStatus"
            >反审核</el-button
          >
        </span>
        <span v-else class="spanwrap">
          <el-button
            type="primary"
            @click="examineHandle()"
            :disabled="dataListSelections.length <= 0"
            >审核</el-button
          >
          <el-button
            type="primary"
            @click="unexamineHandle()"
            :disabled="dataListSelections.length <= 0"
            >反审核</el-button
          >
        </span>
        <!-- <el-button
          type="primary"
          @click="unexamineHandle()"
          :disabled="dataListSelections.length <= 0"
          >打印</el-button
        >
        <el-button
          type="primary"
          @click="unexamineHandle()"
          :disabled="dataListSelections.length <= 0"
          >导出</el-button
        > -->
      </p>
    </div>
    <div class="headInfo">
      <el-form
        :inline="true"
        :model="dataForm"
        @keyup.enter.native="getDataList()"
      >
        <el-form-item class="datetime">
          <em>单据日期</em>
          <div class="block">
            <el-date-picker
              v-model="value1"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="getTime"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          ><em>单据编号</em>
          <el-input
            v-model="dataForm.userID"
            placeholder="单据编号"
            clearable
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item
          ><em>供应商</em>
          <el-select
            v-model="dataForm.organName"
            placeholder="供应商请选择"
            clearable
          >
            <!-- @change="change1($event)" -->
            <el-option
              v-for="item in supplierOptions"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          ><em>采购员</em>
          <el-select
            v-model="dataForm.salesman"
            placeholder="采购员请选择"
            clearable
          >
            <!-- @change="change1($event)" -->
            <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="payType"
          ><em>付款方式</em>
          <el-select
            clearable
            v-model="dataForm.payType"
            placeholder="付款方式请选择"
            @change="change2($event)"
          >
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          ><em>业务类型</em>
          <el-select
            clearable
            v-model="dataForm.workType"
            placeholder="业务类型请选择"
          >
            <el-option
              v-for="item in workTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          ><em>采购订单</em>
          <el-input
            v-model="dataForm.purchaseStockBillNo"
            placeholder="采购订单"
            clearable
            maxlength="15"
          ></el-input>
        </el-form-item>
        <el-form-item
          ><em>单据状态</em>
          <el-select
            clearable
            v-model="dataForm.status"
            placeholder="单据状态请选择"
            @change="change5($event)"
          >
            <el-option
              v-for="item in options5"
              :key="item.value"
              :label="item.label"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <p class="btn">
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetDataList()">重置</el-button>
      </p>
    </div>
    <div class="main">
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%"
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
          show-overflow-tooltip
          width="50px"
        >
        </el-table-column>
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="operTime"
          header-align="center"
          align="center"
          width="150"
          label="单据日期"
        >
        </el-table-column>
        <el-table-column
          prop="externalNumber"
          header-align="center"
          align="center"
          width="150"
          label="采购订单"
        >
        </el-table-column>
        <el-table-column
          prop="number"
          header-align="center"
          align="center"
          width="150"
          label="单据编号"
        >
        </el-table-column>
        <el-table-column
          prop="organName"
          header-align="center"
          align="center"
          label="供应商"
        >
        </el-table-column>
        <el-table-column
          prop="userName"
          header-align="center"
          align="center"
          label="业务员"
        >
        </el-table-column>
        <el-table-column
          prop="subType"
          header-align="center"
          align="center"
          label="业务类型"
        >
        </el-table-column>
        <el-table-column
          prop="userName2"
          header-align="center"
          align="center"
          label="制单人"
        >
        </el-table-column>
        <el-table-column
          prop="totalPrice"
          header-align="center"
          align="center"
          label="总金额"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          header-align="center"
          align="center"
          label="单据状态"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.status == 0 ? "未审核" : "已审核" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              v-if="isAuth('sys:user:update')"
              type="text"
              size="small"
              @click="addOrUpdateHandle(scope.row.id)"
              >查看</el-button
            >
            <el-button
              v-if="scope.row.status == 0"
              type="text"
              size="small"
              @click="addOrUpdateHandle(scope.row.id, 'update')"
              >修改</el-button
            >
            <el-button
              v-if="scope.row.status == 0"
              type="text"
              size="small"
              @click="deleteHandle(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./orderlist-add-or-update";
export default {
  data() {
    return {
      dataForm: {
        organName: "",
        userName: "",
        userID: "",
        value1: "",
        salesman: "",
        payType: "",
        serviceType: "",
        transportType: "",
        workType: "",
        status: "",
        purchaseStockBillNo: "",
      },
      dataList: [],
      supplierOptions: [],
      workTypeOptions: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      examineStatus: true,
      unexamineStatus: true,
      dataListSelections: [],
      addOrUpdateVisible: false,
      value1: [],
      options1: [],
      options2: [
        {
          value: "选项1",
          label: "支付宝",
        },
        {
          value: "选项2",
          label: "微信",
        },
        {
          value: "选项3",
          label: "现金",
        },
        {
          value: "选项4",
          label: "转账",
        },
      ],
      options3: [
        {
          value: "选项1",
          label: "线上",
        },
        {
          value: "选项2",
          label: "线下",
        },
      ],
      options4: [
        {
          value: "选项1",
          label: "平台配送",
        },
        {
          value: "选项2",
          label: "第三方物流",
        },
        {
          value: "选项3",
          label: "上门自提",
        },
      ],
      options5: [
        {
          value: "0",
          label: "待审核",
        },
        {
          value: "1",
          label: "已审核",
        },
      ],
      beginTime: "",
      endTime: "",
    };
  },
  components: {
    AddOrUpdate,
  },
  activated() {
    this.getDataList();
  },
  mounted() {
    this.getsupplier();
    this.getAllSubtype();
  },
  methods: {
    getAllSubtype() {
      this.$http({
        url: this.$http.adornUrl(`/depot/getAllSubtype`),
        method: "get",
      }).then((data) => {
        console.log(data);
        let res = JSON.parse(JSON.stringify(data.data.data));
        res = res.filter((item) => {
          return (item.value = item.id), (item.label = item.sub_type);
        });
        this.workTypeOptions = res;
      });
    },
    getsupplier() {
      let str = `{"supplier":"","type":"供应商","phonenum":"","telephone":"","description":""}`;
      var search = encodeURIComponent(str);
      this.$http({
        url: this.$http.adornUrl(`/supplier/list?search=${search}`),
        method: "get",
        params: this.$http.adornParams({
          currentPage: 1,
          pageSize: 1000,
        }),
      }).then((data) => {
        console.log(data);
        if (data.data && data.data.code === 0) {
          this.supplierOptions = data.data.data.filter((fitem) => {
            // console.log(fitem)
            fitem.value = fitem.id;
            fitem.label = fitem.supplier;
            return fitem;
          });
        }
      });
    },
    getTime() {
      this.beginTime = this.timestampToTime(this.value1[0].getTime());
      this.endTime = this.timestampToTime(this.value1[1].getTime());
      console.log(this.beginTime, this.endTime);
    },
    // 时间戳转成时间
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getHours() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    // 获取数据列表
    getDataList() {
      console.log(this.dataForm.organName.label);
      this.dataListLoading = true;
      this.salesman();
      let type = "入库";
      let subType = "采购";
      let roleType = "全部数据";
      let str = `{"type":"${type}","subType":"${subType}","roleType":"${roleType}","state":"","number":"${
        this.dataForm.userID
      }","buyer":"","organName":"${
        this.dataForm.organName.label || ""
      }","purchaseStockBillNo":"${this.dataForm.purchaseStockBillNo}","purchaseSalesBillNo":"","beginTime":"${
        this.beginTime
      }","endTime":"${this.endTime}","materialParam":"${
        this.dataForm.userName || ""
      }","userName":"${this.dataForm.salesman.label || ""}","payType":"${
        this.dataForm.payType.label || ""
      }","serviceType":"${
        this.dataForm.serviceType.label || ""
      }","transportType":"${
        this.dataForm.transportType.label || ""
      }","status":"${
        this.dataForm.status.value || ""
      }","depotIds":"","deliverDate":"","salesDate":"","billType":"","externalNumber":"","stockType":"","deliveryType":"",deliveryBillNo:"",salesBillNo:"",accountSalesBillno:""}`;
      var search = encodeURIComponent(str);
      this.$http({
        url: this.$http.adornUrl(`/depotHead/list?search=${search}`),
        method: "get",
        params: this.$http.adornParams({
          currentPage: this.pageIndex,
          pageSize: this.pageSize,
        }),
      }).then(({ data }) => {
        // console.log(data);
        if (data && data.code === 0) {
          this.dataList = data.data.list;
          this.totalPage = data.data.totalCount;
          this.dataList.forEach((item) => {
            console.log(item.status);
            // if (item.status == 0) {
            //   item.status = "未审核";
            // } else if (item.status == 1) {
            //   item.status = "已审核";
            // } else if (item.status == 2) {
            //   item.status = "已转销售";
            // }
          });
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 获取业务员下拉
    salesman() {
      this.$http({
        url: this.$http.adornUrl(`/depot/getAllUser`),
        method: "get",
      }).then((data) => {
        console.log(data);
        let res = JSON.parse(JSON.stringify(data.data.data));
        res = res.filter((item) => {
          return (item.value = item.user_id), (item.label = item.username);
        });
        this.options1 = res;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      if (val.length == 1) {
        if (val[0].status == 1) {
          this.examineStatus = true;
          this.unexamineStatus = false;
        }
        if (val[0].status == 0) {
          this.examineStatus = false;
          this.unexamineStatus = true;
        }
      }
      this.dataListSelections = val;
    },
    // 新增 / 修改
    addOrUpdateHandle(id, update) {
      console.log(id, update);
      if (update) {
        this.$router.push({
          path: "/purchase-orderin/orderinadd",
          query: {
            id: id,
            update: update,
          },
        });
      } else {
        this.$router.push({
          path: "/purchase-orderin/orderinadd",
          query: {
            id: id,
          },
        });
      }
      // console.log(id, status, organName, number, operTimeStr);
      // if (status == "未审核") {
      //   status = 0;
      // } else if (status == "已审核") {
      //   status = 1;
      // } else if (status == "已转销售") {
      //   status = 2;
      // }
      // console.log(id, status);
      // if (status != 0) {
      //   this.$alert("已审核和已转的单据不能编辑！", {
      //     dangerouslyUseHTMLString: true,
      //   });
      //   return;
      // }
      // this.addOrUpdateVisible = true;
      // this.$nextTick(() => {
      //   this.$refs.addOrUpdate.init(id, organName, number, operTimeStr);
      // });
    },
    // 删除
    deleteHandle(row, organId) {
      console.log(this.dataListSelections);
      var userIds = row? [row]: this.dataListSelections.map((item) => {
            return item.id;
          });
      console.log(userIds.length);
      var num = "";
      if (userIds.length == 1) {
        if (row) {
          console.log(row)
          num = row.defaultNumber;
        }else{
          console.log(userIds);
          num = "此数据"
        }
        } else {
          num = "这些数据"
        }
      this.$confirm(
        // `确定对[id=${userIds.join(",")}]进行[${row.id ? "删除" : "批量删除"}]操作?`,"提示",
        `确定对${num}进行${userIds.length==1 ? "删除" : "批量删除"}操作?`,"提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        console.log(this.dataListSelections);
        console.log(userIds.length);
        let status = 0;
        this.dataListSelections.map((item) => {
          console.log(item);
          if (item.status == 1) {
            status = 1;
          }
        });
        if (status == 1) {
          this.$message({
            message: "已包含已审核订单，请核对后重新删除",
            type: "warning",
            duration: 1500,
          });
          return;
        }
        if (userIds.length == 1) {
          let ids = ""
          if (row) {
            ids = row.id.toString()
          }else{
            ids = userIds.toString()
          }
          this.$http({
            url: this.$http.adornUrl(`/depotHead/deleteDepotHeadAndDetail`),
            method: "get",
            params: this.$http.adornParams({
              id: ids,
            }),
          }).then(({ data }) => {
            console.log("data is :", data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
              this.$http({
                url: this.$http.adornUrl(`/supplier/updateAdvanceIn`),
                method: "get",
                params: this.$http.adornParams({
                  supplierId: organId,
                  advanceIn: id,
                }),
              }).then((data) => {
                console.log(data);
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        } else {
          var ids = userIds.toString();
          console.log(ids);
          this.$http({
            url: this.$http.adornUrl(
              `/depotHead/batchDeleteDepotHeadAndDetail`
            ),
            method: "get",
            params: this.$http.adornParams({
              ids,
            }),
          }).then(({ data }) => {
            console.log("data is :", data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 审核
    examineHandle(id, organId) {
      var userIds = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${userIds.join(",")}]进行[${id ? "审核" : "批量审核"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        let status = 0;
        this.dataListSelections.map((item) => {
          if (item.status == 1) {
            status = 1;
          }
        });
        if (status == 1) {
          this.$message({
            message: "已包含已审核订单，请核对后重试",
            type: "warning",
            duration: 1500,
          });
        } else {
          this.$http({
            url: this.$http.adornUrl(`/depotHead/batchSetStatus`),
            method: "post",
            data: this.$http.adornData(
              {
                depotHeadIDs: userIds.toString(),
                status: "1",
                type:"入库"
              },
              false
            ),
          }).then(({ data }) => {
            // console.log("data is :", data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 2000,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 反审核
    unexamineHandle(id, organId) {
      var userIds = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${userIds.join(",")}]进行[${id ? "审核" : "批量审核"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        let status = 0;
        this.dataListSelections.map((item) => {
          if (item.status == 0) {
            status = 1;
          }
        });
        if (status == 1) {
          this.$message({
            message: "已包含未审核订单，请核对后重试",
            type: "warning",
            duration: 1500,
          });
        } else {
          this.$http({
            url: this.$http.adornUrl(`/depotHead/batchSetStatus`),
            method: "post",
            data: this.$http.adornData(
              {
                depotHeadIDs: userIds.toString(),
                status: "0",
                type:"入库"
              },
              false
            ),
          }).then(({ data }) => {
            // console.log("data is :", data);
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },

    // 重置
    resetDataList() {
      // console.log(11)
      this.dataForm.userName = "";
      this.dataForm.userID = "";
      this.dataForm.datetimerange = "";
      this.dataForm.salesman = "";
      this.dataForm.payType = "";
      this.dataForm.serviceType = "";
      this.dataForm.transportType = "";
      this.dataForm.status = "";
      this.beginTime = "";
      this.endTime = "";
      this.value1 = [];
      this.getDataList();
    },
  },
};
</script>
<style scoped>
.el-card__body .listHead {
  margin-top: -10px;
  border-bottom: 1px solid #eeeeee;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}
.el-form-item {
  width: 24%;
  justify-content: space-between;
  margin-bottom: 15px;
}
.el-form-item >>> .el-input {
  width: 220px;
}
.el-form-item >>> .el-form-item__content {
  display: flex;
}
.el-form-item >>> .el-form-item__content em {
  width: 100px;
  text-align: right;
  color: #31333d;
  margin-right: 15px;
  font-style: normal;
}
.block .el-date-editor .el-range-input {
  width: 50%;
}
.headInfo {
  margin-top: 20px;
}
.main >>> .el-table th,
.el-table tr {
  background-color: #EBF0F5;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #31333D;
}
.headInfo >>> .el-date-editor .el-range-separator {
    width: 7%;
}
.el-date-editor--datetimerange.el-input, .el-date-editor--datetimerange.el-input__inner{
  width: 280px;
}
.mod-user >>> .el-table__body tr.hover-row>td {
    background-color: #EBF0F5;
}
.headInfo >>> .datetime em{
  width: 58px;
}
.headInfo >>> .btn{
  padding-left: 1375px;
}
.headInfo >>> .btn .el-button{
  /* width: 62px; */
  height: 30px;
  background: #F2F9FF;
  border: 1px solid #3153C8;
  border-radius: 4px;
  text-align: center;
  line-height: 0px;
  color: #3153C8;
}
.headInfo >>> .btn .el-button:first-child{
  background: #3153C8;
  color: #fff;
}
.main{
  margin-top: 10px;
}
.headInfo >>> .payType em{
  text-align: left;
  margin-right: -25px;
}
.listHead >>> .el-button--medium {
  padding: 9px 17px;
}
.listHead >>> .add{
  background: #3153C8;
  color: #fff;
}
.listHead >>> span.spanwrap{
  margin-left: 8px;
}
.listHead >>> .el-button{
    background: #F2F9FF;
    border-radius: 4px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #3153C8;
    border-color:#3153C8;
}
.listHead >>> .is-disabled{
  background: #F5F5F5;
  border-radius: 4px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #999DA3;
  border-color:#dddddd;
}
.listHead >>> .add{
  background: #3153C8;
  border-radius: 4px;
  font-size: 14px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #F8F8F8;
  border-color:#3153C8;
}
</style>
